package com.miage.itrading.server.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.miage.itrading.shared.Const;

public class ConnecteurBDD {

	private static final String	DATABASE	= Const.DATABASE_URL;
	private static final String	USER		= Const.DATABASE_USERNAME;
	private static final String	PASSWORD	= Const.DATABASE_PASSWORD;

	private static Connection	Conn;

	private static Connection connecte() {
		if (Conn == null) {
			try {
				DriverManager.registerDriver(new com.mysql.jdbc.Driver());
				Conn = DriverManager.getConnection(DATABASE, USER, PASSWORD);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return Conn;
	}
	
	public static ResultSet executeQuery(String sql) throws SQLException
	{
		connecte();
		return Conn.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE,
				ResultSet.CONCUR_READ_ONLY)
			.executeQuery(sql);
	}
	
	public static void executeUpdate(String sql) throws SQLException
	{
		connecte();
		Conn.createStatement().executeUpdate(sql);
	}
	
	public static ResultSet executeUpdateReturn(String sql) throws SQLException
	{
		connecte();
		Statement stat = Conn.createStatement();
		stat.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

		return stat.getGeneratedKeys();
	}
}